package com.kkb.shopcenter.controller;


import cn.hutool.http.HttpResponse;
import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;
import com.kkb.shopcenter.api.OrderService;
import com.kkb.shopcenter.common.common.HttpResult;
import com.kkb.shopcenter.common.dto.OrderCount;
import com.kkb.shopcenter.common.dto.OrderTimeDataDto;
import com.kkb.shopcenter.common.exception.DefinitionException;
import com.kkb.shopcenter.common.pojo.OrderDelivery;
import com.kkb.shopcenter.common.pojo.OrderItem;
import com.kkb.shopcenter.common.pojo.SubOrderInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class OrderController {

    private  static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Reference
    private OrderService orderService;


    @GetMapping(value = "/storeOrder")
    public HttpResult getStoreOrder(Long shopId, Integer orderStatus,
                                    @RequestParam(value = "page",defaultValue = "1") int pageNo,
                                    @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        PageInfo<SubOrderInfo> subOrderInfoPageInfo
                = orderService.queryPage(shopId,orderStatus,pageNo,pageSize);
        return HttpResult.success(subOrderInfoPageInfo);
    }

    @GetMapping(value = "/getDetailInfo/{id}")
    public HttpResult getDetailInfo(@PathVariable("id") Long subOrderId){
        List<OrderItem> orderItems = orderService.getDetailInfo(subOrderId);
        if(orderItems!=null&&orderItems.size()<=0){
            return HttpResult.defineError(new DefinitionException("获取商品列表为空"));
        }
        return HttpResult.success(orderItems);

    }

    @GetMapping(value = "/getDeliveryInfo/{id}")
    public HttpResult getDeliverInfo(@PathVariable("id") Long subOrderId){
        OrderDelivery orderDelivery = orderService.getDeliverInfo(subOrderId);
        if(orderDelivery==null){
            return HttpResult.defineError(new DefinitionException("暂无次订单配送信息"));
        }
        return HttpResult.success(orderDelivery);
    }

    @GetMapping("/storeOrder/download")
    public void downloadAllOderder(HttpServletResponse response, Long shopId, Integer orderStatus,
                                   @RequestParam(value = "page",defaultValue = "1") int pageNo,
                                   @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        CsvWriter csvWriter = null;
        OutputStream os = null;
        try{
            os = response.getOutputStream();
            csvWriter = new CsvWriter(os,',', Charset.forName("utf-8"));
            String[] headers = {"ID","订单ID","会员ID","店铺名称","付款时间","地址","创建时间","更新时间"};
            csvWriter.writeRecord(headers);
            PageInfo<SubOrderInfo> subOrderInfos = orderService.queryPage(shopId,orderStatus,pageNo,pageSize);
            List<SubOrderInfo> subOrderInfoList = subOrderInfos.getList();
            int result = 0;
            for(SubOrderInfo subOrderInfo:subOrderInfoList){
                List<String> contentList = new ArrayList<>();
                contentList.add(String.valueOf(subOrderInfo.getId()));
                contentList.add(String.valueOf(subOrderInfo.getOrderId()));
                contentList.add(String.valueOf(subOrderInfo.getMemberId()));
                contentList.add(subOrderInfo.getShopName());
                contentList.add(sdf.format(subOrderInfo.getPayTime()));
                contentList.add(subOrderInfo.getAddress());
                contentList.add(sdf.format(subOrderInfo.getCreateTime()));
                contentList.add(sdf.format(subOrderInfo.getUpdateTime()));

                String[] array = contentList.toArray(new String[contentList.size()]);
                csvWriter.writeRecord(array);
                result++;
            }

            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文

            response.setHeader("Content-Disposition", "attachment;filename=");
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(csvWriter!=null){
                csvWriter.close();
            }
        }
    }

    @GetMapping(value = "/data/count")
    public ResponseEntity selectCount(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        OrderTimeDataDto orderTimeDataDto = orderService.orderTimeDate(shopId);
        return new ResponseEntity(orderTimeDataDto, HttpStatus.OK);
    }

    @GetMapping(value = "/StoreOrder/orderCount")
    public ResponseEntity orderCount(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        OrderCount orderCount = orderService.getOrderCount(shopId);
        return new ResponseEntity(orderCount, HttpStatus.OK);
    }

    @GetMapping(value = "/data/chart")
    public ResponseEntity getChart(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        Map<String,Object> map = orderService.chartCount(shopId);
        return new ResponseEntity(map, HttpStatus.OK);
    }


}
